package com.lee.util;

import java.io.File;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.FileRenamePolicy;

public class FileUpload extends HttpServlet {

	private String webTempPath;

	public void init() {
		webTempPath = getServletContext().getRealPath("/") + "images\\item";
		System.out.println(webTempPath);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, java.io.IOException {
		String itemNo = request.getParameter("itemNo");
		// file limit size of 5 MB
		MultipartRequest mpr = new MultipartRequest(request, webTempPath,
				(5 * 1024 * 1024), new FileRenamePolicy(){
			public File rename(File f) {
				return f;
			}
		});
		Enumeration enum2 = mpr.getFileNames();

		response.setContentType("text/html");
		java.io.PrintWriter out = response.getWriter();

		out.println("<html>");
		out.println("<head>");
		out.println("<title>Servlet upload</title>");
		out.println("</head>");
		out.println("<body>");

		for (int i = 1; enum2.hasMoreElements(); i++) {

			out.println("The name of uploaded file " + i + " is: "
					+ mpr.getFilesystemName((String) enum2.nextElement()) + "/"
					+ itemNo + "<br><br>");
		}
		out.println("</body>");
		out.println("</html>");

	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, java.io.IOException {

		throw new ServletException("GET method used with "
				+ getClass().getName() + ": POST method required.");
	}

}